<template>
  <div class="subject" v-loading="loading">
    <div class="s-left">
      <div class="sl-height">未排产订单</div>
      <div class="sl-cx">
        <div class="sl-input">
          <div class="sl-i">
            <span style="width: 49%">织布单号：</span>
            <el-input style="width: 75%" v-model="query.planOrderCode"></el-input>
          </div>
          <div class="sl-i">
            <span style="width: 49%">坯布编号：</span>
            <el-input style="width: 75%" v-model="query.greyCode"></el-input>
          </div>
        </div>
        <div class="sl-button">
          <el-button type="primary" :icon="Search" @click="getList">查询</el-button>
        </div>
      </div>
      <div class="sl-table">
        <encapsulation-agrid ref="refgridOption" :configaggrid="configaggrid"></encapsulation-agrid>
      </div>
      <div class="trial-calculation">
        <el-button type="primary" @click="trialCalculation">试算</el-button>
      </div>
    </div>
    <div class="s-right">
      <div class="sl-height1">已排产订单</div>
      <div class="sr-header">
        <el-form ref="ruleFormRef" :model="GanttChartQuery" label-width="80px" status-icon inline>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="甘特图时间范围:" prop="start" label-width="120px">
                <el-date-picker
                  v-model="GanttChartQuery.startTime"
                  type="datetime"
                  placeholder="选择开始日期"
                  format="YYYY-MM-DD"
                  value-format="x"
                  style="width: 50%"
                  @change="changeDatePicker"
                />
                <el-date-picker
                  v-model="GanttChartQuery.endTime"
                  type="datetime"
                  placeholder="选择结束日期"
                  format="YYYY-MM-DD"
                  value-format="x"
                  style="width: 50%"
                  @change="changeDatePicker"
                />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="机台:" prop="title" label-width="50px">
                <el-input v-model="GanttChartQuery.machineCode" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="计划单:" prop="title" label-width="60px">
                <el-input v-model="GanttChartQuery.planOrderCode" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="显示方式:" prop="size">
                <el-select v-model="GanttChartQuery.size" @change="inputSize">
                  <el-option label="月" :value="20" />
                  <el-option label="日" :value="16" />
                </el-select> </el-form-item
            ></el-col>
            <el-col :span="4">
              <div class="gttbutton">
                <el-button type="primary" @click="rightClickList">查询</el-button>
                <el-button type="success" @click="save">保存</el-button>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="gtt-color">
        <el-button type="primary" v-show="buttonType == 'TrialCalculation'" @click="newMachine"
          >新增机台</el-button
        >
        <el-button
          type="primary"
          v-show="buttonType == 'TrialCalculation'"
          @click="erasingMachine"
          style="margin-right: 100px"
          >删除机台</el-button
        >
        <div class="gtt-hang">
          <div class="kuai lan"></div>
          <div>已排未保存</div>
        </div>
        <div class="gtt-hang">
          <div class="kuai zi"></div>
          <div>生产进行中</div>
        </div>
        <div class="gtt-hang">
          <div class="kuai lv"></div>
          <div>已排已保存</div>
        </div>
        <div class="gtt-hang">
          <div class="kuai huang"></div>
          <div>未完成</div>
        </div>
      </div>
      <div class="gstc-fater" id="gstc-fater">
        <EncapsulateTheGanttChart
          ref="GanttChartRef"
          :configGanttChart="configGanttChart"
          @rightGanttChart="rightGanttChart"
          @sateMounted="sateMounted"
          @drag="dargGtt"
          :key="componentKey"
        ></EncapsulateTheGanttChart>
      </div>
    </div>
    <el-dialog
      v-model="visibleModify"
      width="10%"
      top="35vh"
      :before-close="
        () => {
          visibleModify = false
        }
      "
    >
      <el-button type="primary" @click="CompletionOfTask">完结</el-button>
      <el-button type="primary" @click="revocation">撤销</el-button>
      <!-- <template #footer>
        <span class="dialog-footer">
          <el-button @click="visibleModify = false">取消</el-button>
          <el-button type="primary" @click="modify"> 保存 </el-button>
        </span>
      </template> -->
    </el-dialog>
    <el-dialog v-model="machineNumberPopover" :width="800" title="选择规则">
      <div style="width: 100%; height: 500px" v-show="MachineOperation == 'new'">
        <encapsulation-agrid
          ref="refgridOption3"
          :configaggrid="configaggrid3"
        ></encapsulation-agrid>
      </div>
      选择机台号:<el-select
        v-show="MachineOperation == 'del'"
        v-model="delMachineCode"
        class="m-2"
        placeholder="选择您要删除的机台号"
        style="width: 50%"
      >
        <el-option
          v-for="(item, index) in machineList"
          :key="index"
          :label="item.machineCode"
          :value="item.machineCode"
        />
      </el-select>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="machineNumberPopover = false">取消</el-button>
          <el-button type="primary" @click="machineNumberOk"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
//elementplus图标
import { Search } from '@element-plus/icons-vue'
//表格列
import { tableColumn } from './tableColumn'

//引入日期处理插件
import dayjs from 'dayjs'
// 引入element提示
import { ElMessage, ElMessageBox } from 'element-plus'
//接机
import { post, get } from '@/api/http'
import EncapsulateTheGanttChart from '@/components/EncapsulateTheGanttChart/index.vue'
// 右键弹窗
const visibleModify = ref(false)
const rightClickData = ref<any>({})
let refgridOption = ref<any>()
let state: any
let gstc: any
const componentKey = ref<Number>(1)
const gstcElement = ref<any>('')
let configaggrid = ref({
  url: 'planSingle/planSchedul/getPageInfo', //接口路径
  queryData: {
    schedulState: 0,
    size: 1000,
  },
  paginationShow: true, //分页是否显示
  invokeiIterface: true, //是否调用接口
  rowMultiSelectWithClick: false, //点击行是否多选
  column: tableColumn,
  queryPage: 1000,
})
//甘特图参数
const GanttChartQuery = ref({
  startTime: dayjs().subtract(1, 'month').startOf('month').valueOf(),
  endTime: dayjs().endOf('month').valueOf(),
  size: 21,
  planOrderCode: '',
  machineCode: '',
})
// 试算数据loading
const loading = ref(false)
// 选择单据
const selectrows = ref<any>([])
// 推荐机台
const machineList = ref([])
// 全部机台
const gtttRows = ref<any>({})
// 全部任务
const gtttItems = ref<any>({})
//按钮类型（试算、查询）
const buttonType = ref<string>('')
//全部推荐机台
const recommendationStand = ref([])
//全部机台
const machineData = ref([])

//未排产参数
const query = ref({
  greyCode: '',
  planOrderCode: '',
})
onMounted(() => {
  getList()
})
// 未排产数据接口
const getList = () => {
  const { greyCode, planOrderCode } = query.value
  let pam: {
    schedulState: Number
    greyCode?: string
    planOrderCode?: string
    size: Number
  } = {
    size: 1000,
    schedulState: 0,
  }
  // if (gstc) gstc.destroy()
  if (greyCode) {
    pam.greyCode = greyCode
  }
  if (planOrderCode) {
    pam.planOrderCode = planOrderCode
  }
  refgridOption.value.setQuery(pam)
}
let refgridOption3 = ref<any>()
let configaggrid3 = ref({
  url: '', //接口路径
  paginationShow: false, //分页是否显示
  invokeiIterface: false, //是否调用接口
  rowMultiSelectWithClick: false, //点击行是否多选
  column: [
    {
      headerCheckboxSelection: true,
      checkboxSelection: true,
      width: 50,
      showDisabledCheckboxes: false,
      pinned: 'left',
    },
    {
      headerName: '机台号',
      field: 'machineCode',
      width: 180,
    },
    {
      headerName: '楼层',
      field: 'areaName',
      width: 180,
    },
    {
      headerName: '公司',
      field: 'firm',
      width: 300,
    },
  ],
  queryData: {},
})
//试算按钮
// 1. 推荐机台planSingle/planSchedul/getAutoScheduleInfo
// 2. 拿到旧任务planSingle/planSchedul/getGanttInfo
// 3.试算拿到新任务planSingle/planSchedul/getScheduleCalculate
const trialCalculation = async () => {
  let arr3 = refgridOption.value.getSelectedRows()
  if (arr3.length == 0) {
    ElMessage.error('请先勾选单据')
    return
  }

  buttonType.value = 'TrialCalculation'
  // arr3[0].planOrderId = arr3[0].id
  selectrows.value = arr3
  try {
    loading.value = true
    let { code, message, data } = await post({
      url: 'planSingle/planSchedul/getAutoScheduleInfo',
      data: arr3[0],
    })
    if (code == 200) {
      recommendationStand.value = data.machineData
      let pam = []
      if (data.machineNum > data.machineData.length) {
        pam = data.machineData
      } else {
        for (var i = 0; i < data.machineNum; i++) {
          pam.push(data.machineData[i])
        }
      }
      gtttRows.value = {}
      gtttItems.value = {}
      GanttChartRef.value.oldTaskIds = []
      machineData.value = data.machineData
      machineList.value = pam
      oldTask()
      loading.value = false
      return
    }
    ElMessage.error(message)
    loading.value = false
  } finally {
    loading.value = false
  }
}
//旧任务接口
const oldTask = async () => {
  try {
    loading.value = true
    let { code, message, data } = await post({
      url: 'planSingle/planSchedul/getGanttInfo',
      data: machineList.value,
    })
    if (code == 200) {
      gtttRows.value = {}
      gtttItems.value = {}
      GanttChartRef.value.oldTaskIds = []
      for (let key in data) {
        gtttRows.value['gstcid-' + key] = {
          id: 'gstcid-' + key,
          label: key,
          type: 'old',
        }
        for (let key1 in data[key]) {
          let { id, startTime, endTime, finishState, weight, weavDeliveryDate } = data[key][key1]
          gtttItems.value[id] = {
            id: id,
            // label: startTime + ' 至 ' + endTime,
            label:
              dayjs(startTime).valueOf() > dayjs(weavDeliveryDate).valueOf()
                ? ' 任务超期 ' + weight + ' KG '
                : weight + ' KG ',
            rowId: 'gstcid-' + key,
            time: {
              start: dayjs(startTime).valueOf(),
              end: dayjs(endTime).valueOf(),
            },
            type: 'old',
            list: data[key][key1],
            drag: finishState == 1 ? false : true, //是否可纵向拖拉
            // frozen: finishState == 1 ? false : true, //是否可横向拖拉
            frozen: false, //是否可横向拖拉
            style: { background: finishState == 0 ? '#ccc' : finishState == 1 ? '#a024fe' : '' },
          }
        }
      }
      componentKey.value += 1
      newTask()
      nextTick(() => {
        loading.value = false
      })
      return
    }
    ElMessage.error(message)
    loading.value = false
  } finally {
    loading.value = false
  }
}
//新任务（试算）接口
const newTask = async () => {
  // console.log(selectrows.value[0].orderDeliveryDate)
  // console.log(selectrows.value[0].weavDeliveryDate)
  try {
    loading.value = true
    let { code, message, data } = await post({
      url: 'planSingle/planSchedul/getScheduleCalculate',
      data: {
        planOrderId: selectrows.value[0].planId,
        planOrderCode: selectrows.value[0].planOrderCode.split('/')[0],
        // weight: selectrows.value[0].orderWeight,
        greyId: selectrows.value[0].greyId,
        greyCode: selectrows.value[0].greyCode,
        greyName: selectrows.value[0].greyName,
        productType: selectrows.value[0].productType,
        weavDeliveryDate: selectrows.value[0].orderDeliveryDate,
        calculateData: [],
        machine: machineList.value,
        orderWeightNew: Math.abs(Number(selectrows.value[0].orderWeight)),
      },
    })
    if (code == 200) {
      let ids: Number[] = []
      for (let key in gtttItems.value) {
        for (let key1 in gtttItems.value[key]) {
          const { id } = gtttItems.value[key]
          ids.push(id)
        }
      }
      let ids1 = [...new Set(ids)]
      if (gtttItems.value.length == 0 || ids1.length == 0) {
        ids1.push(0)
      }
      data.map((item: any) => {
        const { machineCode, alreadyWeight, startTime, endTime, weavDeliveryDate } = item
        ids1.sort((a, b) => Number(a) - Number(b))
        gtttRows.value['gstcid-' + machineCode] = {
          id: 'gstcid-' + machineCode,
          label: machineCode,
          type: 'new',
        }
        let id = ids1[ids1.length - 1]
        gtttItems.value[Number(id) + 1] = {
          id: Number(id) + 1,
          label:
            dayjs(startTime).valueOf() > dayjs(weavDeliveryDate).valueOf()
              ? ' 任务超期 ' + alreadyWeight + ' KG '
              : alreadyWeight + ' KG ',
          rowId: 'gstcid-' + machineCode,
          time: {
            start: dayjs(startTime).valueOf(),
            end: dayjs(endTime).valueOf(),
          },
          type: 'new',
          style: { background: '#5191fd' },
          drag: true, //是否可纵向拖拉
          // frozen: true, //是否可横向拖拉
          frozen: false, //是否可横向拖拉

          list: item,
        }
        ids1.push(Number(id) + 1)
      })
      // if (gstc && gstc.destroy) gstc.destroy()
      // getSate()
      // console.log(componentKey.value)
      nextTick(() => {
        // console.log(gtttRows.value)
        // console.log(gtttItems.value)
        state.update('config.chart.time.from', GanttChartQuery.value.startTime)
        state.update('config.chart.time.to', GanttChartQuery.value.endTime)
        state.update('config.chart.time.zoom', GanttChartQuery.value.size)
        state.update('config.list.rows', gtttRows.value)
        state.update('config.chart.items', gtttItems.value)
        loading.value = false
      })
      return
    }
    ElMessage.error(message)
    loading.value = false
  } finally {
    loading.value = false
  }
}
//保存
const save = () => {
  if (buttonType.value == 'TrialCalculation') {
    // 旧任务
    oldTaskEvent()
    //新任务
    newTaskEvent()
  }
  if (buttonType.value == 'QueryTheGanttChart') {
    // 查询任务
    queryInterface()
  }
  // planSingle/planSchedul/getScheduleSave
}
//修改任务
const queryInterface = () => {
  //拿到全部任務
  let Items = Object.values(gstc.api.getAllItems())
  // console.log(Items)
  // 拿到旧任务修改
  let oldItems = Items.filter((item: any) => {
    return item.type == 'old'
  })
  let ids = [...new Set(GanttChartRef.value.oldTaskIds)]

  if (ids.length == 0) {
    return
  }
  //拖动的旧任务
  let dragTheOldTask: any[] = []
  ids.map((id) => {
    oldItems.map((item: any) => {
      if (id == item.id) {
        dragTheOldTask.push(item)
      }
    })
  })
  // console.log(dragTheOldTask)
  let oldParameter = dragTheOldTask.reduce((pre: any, cur: any) => {
    const {
      time: { start, end },
      list,
      rowId,
    } = cur
    list.startTime = dayjs(start).format('YYYY-MM-DD HH:mm:ss')
    list.endTime = dayjs(end).format('YYYY-MM-DD HH:mm:ss')
    list.newMachineCode = rowId.split('gstcid-')[1]
    return pre.concat(cur.list)
  }, [])
  // oldTaskInterface(oldParameter)
  querysaveinterface(oldParameter)
  // console.log(oldParameter)
}
//查询保存接口
const querysaveinterface = async (oldParameter: any[]) => {
  try {
    loading.value = true
    let { code, message } = await post({
      url: 'planSingle/planMachineTask/ganttCalculateSave',
      data: oldParameter,
    })
    if (code == 200) {
      reateDeta()
      ElMessage.success('保存成功')
      loading.value = false
      return
    }
    ElMessage.error(message)
    loading.value = false
  } finally {
    loading.value = false
  }
}
const reateDeta = () => {
  gtttRows.value = {}
  gtttItems.value = {}
  GanttChartRef.value.oldTaskIds = []
  componentKey.value += 1
  nextTick(() => {
    state.update('config.chart.time.from', GanttChartQuery.value.startTime)
    state.update('config.chart.time.to', GanttChartQuery.value.endTime)
    state.update('config.chart.time.zoom', GanttChartQuery.value.size)
    state.update('config.list.rows', gtttRows.value)
    state.update('config.chart.items', gtttItems.value)
  })
}
//旧任务事件
const oldTaskEvent = () => {
  //拿到全部任務

  let Items = Object.values(gstc.api.getAllItems())
  // console.log(Items)
  // 拿到旧任务修改
  let oldItems = Items.filter((item: any) => {
    return item.type == 'old'
  })
  let ids = [...new Set(GanttChartRef.value.oldTaskIds)]

  if (ids.length == 0) {
    return
  }
  //拖动的旧任务
  let dragTheOldTask: any[] = []
  ids.map((id) => {
    oldItems.map((item: any) => {
      if (id == item.id) {
        dragTheOldTask.push(item)
      }
    })
  })
  //旧任务参数
  const { greyCode, greyName, planOrderCode, planOrderId, greyId } = selectrows.value[0]
  let oldParameter = {
    greyCode,
    greyName,
    planOrderCode,
    planOrderId,
    greyId,
    save: [],
  }
  oldParameter.save = dragTheOldTask.reduce((pre: any, cur: any) => {
    const {
      time: { start, end },
      rowId: resId,
      list,
    } = cur
    let rowid = resId.split('gstcid-')[1]
    // 拿到当前机台信息
    let machineCodeList = recommendationStand.value.filter((item: any) => {
      return item.machineCode == rowid
    })
    // 判断no数值进行事件计算以及type赋值
    const {
      no,
      machineName,
      firm,
      areaName,
      firmId,
      machineTypeId,
      coordinate,
      machineCode,
      machineTypeName,
      storey,
      areaId,
    } = machineCodeList[0]
    if (no == 1) {
      //两个小时时间戳
      let TwoHourTimeStamp = 3600 * 1000 * 2
      //计算后的时间
      let AfterCalculationStart = dayjs(start + TwoHourTimeStamp).format('YYYY-MM-DD HH:mm:ss')
      let AfterCalculationEnd = dayjs(end + TwoHourTimeStamp).format('YYYY-MM-DD HH:mm:ss')
      list.startTime = AfterCalculationStart
      list.endTime = AfterCalculationEnd
      list.maintainType = '转单'
    }
    if (no == 2) {
      //2.5个小时时间戳
      let TwoHourTimeStamp = 3600 * 1000 * 2.5
      //计算后的时间
      let AfterCalculationStart = dayjs(start + TwoHourTimeStamp).format('YYYY-MM-DD HH:mm:ss')
      let AfterCalculationEnd = dayjs(end + TwoHourTimeStamp).format('YYYY-MM-DD HH:mm:ss')
      list.startTime = AfterCalculationStart
      list.endTime = AfterCalculationEnd
      list.maintainType = '改纱长'
    }
    if (no == 3) {
      //5个小时时间戳
      let TwoHourTimeStamp = 3600 * 1000 * 5
      //计算后的时间
      let AfterCalculationStart = dayjs(start + TwoHourTimeStamp).format('YYYY-MM-DD HH:mm:ss')
      let AfterCalculationEnd = dayjs(end + TwoHourTimeStamp).format('YYYY-MM-DD HH:mm:ss')
      list.startTime = AfterCalculationStart
      list.endTime = AfterCalculationEnd
      list.maintainType = '改三角'
    }
    if (no == 4) {
      //7.5个小时时间戳
      let TwoHourTimeStamp = 3600 * 1000 * 7.5
      //计算后的时间
      let AfterCalculationStart = dayjs(start + TwoHourTimeStamp).format('YYYY-MM-DD HH:mm:ss')
      let AfterCalculationEnd = dayjs(end + TwoHourTimeStamp).format('YYYY-MM-DD HH:mm:ss')
      list.startTime = AfterCalculationStart
      list.endTime = AfterCalculationEnd
      list.maintainType = '换针筒'
    }
    if (no == 5) {
      //9个小时时间戳
      let TwoHourTimeStamp = 3600 * 1000 * 9
      //计算后的时间
      let AfterCalculationStart = dayjs(start + TwoHourTimeStamp).format('YYYY-MM-DD HH:mm:ss')
      let AfterCalculationEnd = dayjs(end + TwoHourTimeStamp).format('YYYY-MM-DD HH:mm:ss')
      list.startTime = AfterCalculationStart
      list.endTime = AfterCalculationEnd
      list.maintainType = '转配套'
    }
    //把拖动后的机台赋值给之前初始化的机台信息
    list.no = no
    list.machineName = machineName
    list.firm = firm
    list.areaName = areaName
    list.firmId = firmId
    list.machineTypeId = machineTypeId
    list.coordinate = coordinate
    list.machineCode = machineCode
    list.machineTypeName = machineTypeName
    list.storey = storey
    list.areaId = areaId
    return pre.concat(cur.list)
  }, [])
  oldTaskInterface(oldParameter)
}
// 修改任务接口
const oldTaskInterface = async (oldParameter: any) => {
  try {
    loading.value = true
    let { code, message, data } = await post({
      url: 'planSingle/planMachineTask/ganttSave',
      data: oldParameter,
    })
    if (code == 200) {
      reateDeta()
      ElMessage.success('保存成功')
      loading.value = false
      return
    }
    ElMessage.error(message)
    loading.value = false
  } finally {
    loading.value = false
  }
}
// 新任务事件
const newTaskEvent = () => {
  //拿到全部任務
  let Items = Object.values(gstc.api.getAllItems())
  // console.log(Items)
  // 拿到新任务新增
  let newItems = Items.filter((item: any) => {
    return item.type == 'new'
  })
  if (newItems.length == 0) {
    return
  }
  //新任务参数
  const { greyCode, greyName, planOrderCode, planOrderId, greyId } = selectrows.value[0]
  let newParameter: any = {
    greyCode,
    greyName,
    planOrderCode,
    planOrderId,
    greyId,
    save: [],
  }
  newParameter.save = newItems.reduce((pre: any, cur: any) => {
    const {
      time: { start, end },
      rowId: resId,
      list,
    } = cur
    let rowid = resId.split('gstcid-')[1]
    // 拿到当前机台信息
    let machineCodeList = recommendationStand.value.filter((item: any) => {
      return item.machineCode == rowid
    })
    // 判断no数值进行事件计算以及type赋值
    const {
      no,
      machineName,
      firm,
      areaName,
      firmId,
      machineTypeId,
      coordinate,
      machineCode,
      machineTypeName,
      storey,
      areaId,
    } = machineCodeList[0]
    if (no == 1) {
      //两个小时时间戳
      let TwoHourTimeStamp = 3600 * 1000 * 2
      //计算后的时间
      let AfterCalculationStart = dayjs(start + TwoHourTimeStamp).format('YYYY-MM-DD HH:mm:ss')
      let AfterCalculationEnd = dayjs(end + TwoHourTimeStamp).format('YYYY-MM-DD HH:mm:ss')
      list.startTime = AfterCalculationStart
      list.endTime = AfterCalculationEnd
      list.maintainType = '转单'
    }
    if (no == 2) {
      //2.5个小时时间戳
      let TwoHourTimeStamp = 3600 * 1000 * 2.5
      //计算后的时间
      let AfterCalculationStart = dayjs(start + TwoHourTimeStamp).format('YYYY-MM-DD HH:mm:ss')
      let AfterCalculationEnd = dayjs(end + TwoHourTimeStamp).format('YYYY-MM-DD HH:mm:ss')
      list.startTime = AfterCalculationStart
      list.endTime = AfterCalculationEnd
      list.maintainType = '改纱长'
    }
    if (no == 3) {
      //5个小时时间戳
      let TwoHourTimeStamp = 3600 * 1000 * 5
      //计算后的时间
      let AfterCalculationStart = dayjs(start + TwoHourTimeStamp).format('YYYY-MM-DD HH:mm:ss')
      let AfterCalculationEnd = dayjs(end + TwoHourTimeStamp).format('YYYY-MM-DD HH:mm:ss')
      list.startTime = AfterCalculationStart
      list.endTime = AfterCalculationEnd
      list.maintainType = '改三角'
    }
    if (no == 4) {
      //7.5个小时时间戳
      let TwoHourTimeStamp = 3600 * 1000 * 7.5
      //计算后的时间
      let AfterCalculationStart = dayjs(start + TwoHourTimeStamp).format('YYYY-MM-DD HH:mm:ss')
      let AfterCalculationEnd = dayjs(end + TwoHourTimeStamp).format('YYYY-MM-DD HH:mm:ss')
      list.startTime = AfterCalculationStart
      list.endTime = AfterCalculationEnd
      list.maintainType = '换针筒'
    }
    if (no == 5) {
      //9个小时时间戳
      let TwoHourTimeStamp = 3600 * 1000 * 9
      //计算后的时间
      let AfterCalculationStart = dayjs(start + TwoHourTimeStamp).format('YYYY-MM-DD HH:mm:ss')
      let AfterCalculationEnd = dayjs(end + TwoHourTimeStamp).format('YYYY-MM-DD HH:mm:ss')
      list.startTime = AfterCalculationStart
      list.endTime = AfterCalculationEnd
      list.maintainType = '转配套'
    }
    //把拖动后的机台赋值给之前初始化的机台信息
    list.no = no
    list.machineName = machineName
    list.firm = firm
    list.areaName = areaName
    list.firmId = firmId
    list.machineTypeId = machineTypeId
    list.coordinate = coordinate
    list.machineCode = machineCode
    list.machineTypeName = machineTypeName
    list.storey = storey
    list.areaId = areaId
    return pre.concat(cur.list)
  }, [])
  NewTaskInterface(newParameter)
}
// 新增任务接口
const NewTaskInterface = async (newParameter: any) => {
  try {
    loading.value = true
    let { code, message, data } = await post({
      url: 'planSingle/planSchedul/getScheduleSave',
      data: newParameter,
    })
    if (code == 200) {
      reateDeta()
      ElMessage.success('保存成功')
      loading.value = false
      return
    }
    ElMessage.error(message)
    loading.value = false
  } finally {
    loading.value = false
  }
}
//任务完结
const CompletionOfTask = async () => {
  const { id } = rightClickData.value
  try {
    loading.value = true
    let { code, message, data } = await post({
      url: 'planSingle/planMachineTask/ganttDataFinish',
      data: rightClickData.value.list,
    })
    if (code == 200) {
      state.update(`config.chart.items.${id}`, (row: any) => {
        row.style = { background: '#5191fd' }
        return row
      })
      ElMessage.success('完结成功')
      visibleModify.value = false
      loading.value = false
      return
    }
    ElMessage.error(message)
    loading.value = false
  } finally {
    loading.value = false
  }
  visibleModify.value = false
}
//任务撤销
const revocation = async () => {
  const { id } = rightClickData.value
  try {
    loading.value = true
    let { code, message, data } = await post({
      url: 'planSingle/planMachineTask/ganttDataRecall',
      data: rightClickData.value.list,
    })
    if (code == 200) {
      state.update(`config.chart.items.${id}`, (row: any) => {
        row.style = { background: '#ccc' }
        return row
      })
      ElMessage.success('撤销成功')
      visibleModify.value = false
      loading.value = false
      return
    }
    ElMessage.error(message)
    loading.value = false
  } finally {
    loading.value = false
  }
  visibleModify.value = false
}

const rightClickList = async () => {
  buttonType.value = 'QueryTheGanttChart'
  const { endTime, startTime, planOrderCode, machineCode } = GanttChartQuery.value
  componentKey.value += 1
  try {
    loading.value = true
    let { code, message, data } = await post({
      url: 'planSingle/planSchedul/getGanttByCondition',
      data: {
        endTime: dayjs(endTime).format('YYYY-MM-DD HH:mm:ss'),
        startTime: dayjs(startTime).format('YYYY-MM-DD HH:mm:ss'),
        planOrderCode,
        machineCode,
      },
    })
    if (code == 200) {
      gtttRows.value = {}
      gtttItems.value = {}
      GanttChartRef.value.oldTaskIds = []

      // let ids: Number[] = [0]
      for (let key in data) {
        gtttRows.value['gstcid-' + key] = {
          id: 'gstcid-' + key,
          label: key,
          type: 'old',
        }
        for (let key1 in data[key]) {
          let { id, startTime, endTime, finishState, weight, weavDeliveryDate } = data[key][key1]
          // ids.sort((a, b) => Number(a) - Number(b))
          // let num = Number(ids[ids.length - 1]) + 1
          // gtttItems.value[num] = {
          gtttItems.value[id] = {
            // id: num,
            id: id,
            // label: startTime + ' 至 ' + endTime,
            label:
              dayjs(startTime).valueOf() > dayjs(weavDeliveryDate).valueOf()
                ? ' 任务超期 ' + weight + ' KG '
                : weight + ' KG ',
            rowId: 'gstcid-' + key,
            time: {
              start: dayjs(startTime).valueOf(),
              end: dayjs(endTime).valueOf(),
            },
            type: 'old',
            list: data[key][key1],
            drag: finishState == 1 ? false : true, //是否可纵向拖拉
            // frozen: finishState == 1 ? false : true, //是否可横向拖拉
            frozen: false, //是否可横向拖拉

            style: { background: finishState == 0 ? '#ccc' : finishState == 1 ? '#a024fe' : '' },
          }
          // ids.push(num)
        }
      }
      // console.log(gtttRows.value)
      // console.log(state.update)
      // console.log(componentKey.value)
      nextTick(() => {
        state.update('config.chart.time.from', GanttChartQuery.value.startTime)
        state.update('config.chart.time.to', GanttChartQuery.value.endTime)
        state.update('config.chart.time.zoom', GanttChartQuery.value.size)
        state.update('config.list.rows', gtttRows.value)
        state.update('config.chart.items', gtttItems.value)
        loading.value = false
      })
      return
    }
    ElMessage.error(message)
    loading.value = false
  } finally {
    loading.value = false
  }
}
//缩放值更改事件
const inputSize = (val: string) => {
  state.update('config.chart.time.zoom', val)
}
//时间更改事件
const changeDatePicker = (val: string) => {
  state.update('config.chart.time.from', GanttChartQuery.value.startTime)
  state.update('config.chart.time.to', GanttChartQuery.value.endTime)
}

const GanttChartRef = ref()
let configGanttChart = ref({
  startTime: GanttChartQuery.value.startTime,
  endTime: GanttChartQuery.value.endTime,
  size: GanttChartQuery.value.size,
})
//初始事件
let sateMounted = (state1: any, gstc1: any) => {
  state = state1
  gstc = gstc1
}
const dargGtt = async (pam: any) => {
  // console.log(pam)
  try {
    loading.value = true
    let { code, message, data } = await post({
      url: 'planSingle/planMachineTask/getDragInfo',
      data: pam,
    })
    if (code == 200) {
      // console.log(data)
      data.map((item: any) => {
        // console.log(item.id)
        state.update(`config.chart.items.${item.id}`, (row: any) => {
          ;(row.label =
            dayjs(item.startTime).valueOf() > dayjs(item.weavDeliveryDate).valueOf()
              ? ' 任务超期 ' + item.weight + ' KG '
              : item.weight + ' KG '),
            (row.time.start = dayjs(item.startTime).valueOf())
          row.time.end = dayjs(item.endTime).valueOf()
          return row
        })
      })
      loading.value = false
      return
    }
    ElMessage.error(message)
    loading.value = false
  } finally {
    loading.value = false
  }
}
//右键事件
const rightGanttChart = (data: any) => {
  rightClickData.value = data
  visibleModify.value = true
}
//机台号弹窗
const machineNumberPopover = ref(false)
//机台操作状态
const MachineOperation = ref('')
//选择删除的机台
const delMachineCode = ref('')
//新增机台号
const newMachine = () => {
  let arr = refgridOption.value.getSelectedRows()
  if (arr.length == 0) {
    ElMessage.warning('请勾选您的订单')
    return
  }
  MachineOperation.value = 'new'
  machineNumberPopover.value = true
  nextTick(() => {
    refgridOption3.value.setdataListIterface(machineData.value)
  })
}
//保存机台号
const machineNumberOk = () => {
  if (MachineOperation.value == 'new') {
    let arr = refgridOption3.value.getSelectedRows()
    if (arr.length == 0) {
      ElMessage.warning('请勾选您的机台')
      return
    }
    let stuat = machineList.value.some((item: any) => {
      return arr[0].machineCode == item.machineCode
    })
    if (stuat) {
      ElMessage.warning('机台号已存在')
      return
    }
    machineList.value.push(arr[0])
    oldTask()
    nextTick(() => {
      machineNumberPopover.value = false
    })
  }
  if (MachineOperation.value == 'del') {
    if (!delMachineCode.value) {
      ElMessage.warning('请选择您要删除的机台号')
      return
    }
    // console.log(delMachineCode.value)
    machineList.value = machineList.value.filter(
      (val: any) => val.machineCode !== delMachineCode.value
    )
    // console.log(machineList.value)
    oldTask()
    nextTick(() => {
      machineNumberPopover.value = false
    })
  }
}
//删除机台号
const erasingMachine = () => {
  let arr = refgridOption.value.getSelectedRows()
  if (arr.length == 0) {
    ElMessage.warning('请勾选您的订单')
    return
  }
  delMachineCode.value = ''
  MachineOperation.value = 'del'
  machineNumberPopover.value = true
}
</script>

<style lang="scss" scoped>
.subject {
  width: 100%;
  height: 100%;
  background: #f2f7ff;
  box-sizing: border-box;
  display: flex;
  padding: 5px;
}
.s-left {
  width: 23%;
  background: #fff;
  margin-right: 20px;
  border-radius: 10px;
}
.s-right {
  width: 77%;
  background: #fff;
  border-radius: 10px;
}
.sl-height {
  width: 100%;
  height: 45px;
  background: #ff6837;
  border-radius: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 18px;
  color: #fff;
  font-weight: 600;
}

.sl-height1 {
  width: 100%;
  height: 45px;
  background: #5191fd;
  border-radius: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 18px;
  color: #fff;
  font-weight: 600;
}
.sl-input {
  width: 70%;
}
.sl-i {
  display: flex;
  width: 100%;
  justify-content: center;
  align-items: center;
  margin-top: 10px;
  margin-left: 10px;
}
.sl-cx {
  margin-top: 20px;
  display: flex;
}
.sl-button {
  width: 40%;
  display: flex; 
  justify-content: center;
  align-items: center;
}
.sl-table {
  width: 100%;
  height: 70%;
  padding: 20px;
  margin-top: 15px;
}
.trial-calculation {
  width: 100%;
  margin-top: 5%;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-left: -10%;
}
.sr-header {
  width: 100%;
  height: 70px;
  border-bottom: 1px dashed #aba4a4;
}
:deep(.el-form--inline .el-form-item) {
  margin-right: 0px;
}
:deep(.el-form-item) {
  margin-bottom: 0;
}
.sr-header {
  display: flex;
  justify-content: center;
  align-items: center;
}
.gtt-color {
  width: 100%;
  height: 50px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.kuai {
  width: 15px;
  height: 15px;
  border-radius: 2px;
  margin-right: 5px;
}
.gtt-hang {
  height: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 30px;
  color: #aba4a4;
}
.lan {
  background: #5191fd;
}
.zi {
  background: #a024fe;
}
.lv {
  background: #7cee51;
}
.huang {
  background: #ccc;
}
.gstc-fater {
  width: 100%;
  height: 78%;
  padding: 0 20px;
  margin-top:20px;
}
.gstc-wrapper {
  width: 100%;
  height: 100%;
}

// CSS 样式
.ag-cell .wrap-text {
  white-space: pre-wrap; /* 这个属性可以让文本自动换行 */
}
.wrap-text {
  white-space: pre-wrap; /* 这个属性可以让文本自动换行 */
}
// :deep(.gstc){
//   height: 640px !important;
// }
// .gstc__list
</style>